package com.wangrui.consumer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wangrui.inventory.ProductStoreService;
import com.wangrui.consumer.entity.Order;
import com.wangrui.consumer.service.OrderService;
import com.wangrui.consumer.mapper.OrderMapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
* @author Administrator
* @description 针对表【t_order】的数据库操作Service实现
* @createDate 2024-11-17 18:15:53
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
    implements OrderService{
    @DubboReference
    private ProductStoreService productStoreService;

    @GlobalTransactional
    @Override
    public void addOrder(Long productId, Integer num){
        BigDecimal productPrice = productStoreService.getProductPrice(productId);
        Order order = new Order();
        order.setProductId(productId);
        order.setNum(num);
        order.setRemark("");
        order.setUserId(100L);
        order.setOrderDate(new Date());
        order.setAmount(productPrice.multiply(new BigDecimal(num)));
        save(order);
        try {
            productStoreService.reduceStore(productId, num);
        }catch (Exception e){
            System.out.println("注意这里不能把异常吞掉，否则无法实现事务回滚:"+e.getMessage());
            throw e;
        }
        //两种测试方式：1.在consumer端抛异常 2.在provider端抛异常（consumer不要吞异常） 结果：都能保证事务的原子性
//        if(productId == 1){
//            throw new RuntimeException("provider exception");
//        }
    }
}




